package com.wanmait.mavendemo.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils
{
    //读取Cookie
    public static String getCookie(String name, HttpServletRequest request)
    {
        Cookie[] cookies = request.getCookies();
        if(cookies==null)
        {
            return null;
        }
        for(Cookie cookie:cookies)
        {
            String cookieName = cookie.getName();
            if(cookieName.equals(name))
            {
                return cookie.getValue();
            }
        }

        return null;
    }

    //path=/abc只在请求 /abc开头的路径时会在请求头中携带cookie
    // path=/  对整个项目都起作用
    //生成Cookie
    public static void addCookie(String name, String value,String path,int age, HttpServletResponse response)
    {
        Cookie cookie = new Cookie(name,value);
        //设置起作用的路径
        cookie.setPath(path);
        //设置生命周期
        cookie.setMaxAge(age);
        //发送cookie
        response.addCookie(cookie);
    }
}
